package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.dao.BrandMapper;
import com.changgou.goods.dao.CategoryMapper;
import com.changgou.goods.dao.SkuMapper;
import com.changgou.goods.dao.SpuMapper;
import com.changgou.goods.pojo.*;
import com.changgou.goods.dao.CategoryBrandMapper;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 查询全部列表
     *
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public Spu findById(String id) {
        return spuMapper.selectByPrimaryKey(id);
    }


    /**
     * 增加
     *
     * @param spu
     */
    @Override
    public void add(Spu spu) {
        spuMapper.insert(spu);
    }


    /**
     * 修改
     *
     * @param spu
     */
    @Override
    public void update(Spu spu) {
        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void delete(String id) {
        spuMapper.deleteByPrimaryKey(id);
    }


    /**
     * 条件查询
     *
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        return (Page<Spu>) spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     *
     * @param searchMap 查询条件
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        return (Page<Spu>) spuMapper.selectByExample(example);
    }

    @Transactional
    @Override
    public void addGoods(Goods goods) {
        //1.保存spu数据
        goods.getSpu().setId(String.valueOf(idWorker.nextId()));//使用分布式ID代替表得自增主键ID
        spuMapper.insertSelective(goods.getSpu());
        //2.保存sku列表数据
        saveSkuList(goods);

    }

    private void saveSkuList(Goods goods) {
        //保存sku数据
        Spu spu = goods.getSpu();
        Integer brandId = spu.getBrandId();
        //根据ID查询品牌数据
        Brand brand = brandMapper.selectByPrimaryKey(brandId);

        List<Sku> skuList = goods.getSkuList();

        Integer category3Id = spu.getCategory3Id();
        //根据三级分类查询分类数据
        Category category = categoryMapper.selectByPrimaryKey(category3Id);
        //处理分类与品牌关系，如果brandId 和 categoryId 在中间表不存在则插入
        if (brandId != null && category != null) {
            CategoryBrand categoryBrand = new CategoryBrand();
            categoryBrand.setCategoryId(category3Id);
            categoryBrand.setBrandId(brandId);
            int count = categoryBrandMapper.selectCount(categoryBrand);//查询条数

            if (count == 0) {
                categoryBrandMapper.insertSelective(categoryBrand);//新增关联关系
            }
        }


        if (skuList != null && skuList.size() > 0) {
            for (Sku sku : skuList) {
                sku.setId(String.valueOf(idWorker.nextId()));//使用分布式ID代替表得自增主键ID
                sku.setCreateTime(new Date());//创建时间
                sku.setUpdateTime(new Date());//更新时间
                sku.setSpuId(spu.getId()); //设置spuID

                if (StringUtils.isEmpty(sku.getSpec())) { //判断spec的值为空的情况下特殊处理
                    sku.setSpec("{}");
                }
                String name = spu.getName();
                Map<String, String> SpecMap = JSON.parseObject(sku.getSpec(), Map.class);
                if (SpecMap.size() > 0) {
                    for (String key : SpecMap.keySet()) {
                        String specVal = SpecMap.get(key);
                        name += " " + specVal;
                    }
                    sku.setName(name);
                }

                //brandName
                if (brand != null) {
                    sku.setBrandName(brand.getName());
                }
                if (category != null) {
                    sku.setCategoryId(category3Id);//设置三级分类ID
                    sku.setCategoryName(category.getName());//设置三级分类的名称
                }
                skuMapper.insertSelective(sku);
            }
        }
    }
    @Transactional
    @Override
    public void updateGoods(Goods goods) {

        //1.更新spu数据
        spuMapper.updateByPrimaryKeySelective(goods.getSpu());

        //2.根据spuId删除库中的sku数据
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",goods.getSpu().getId());
        skuMapper.deleteByExample(example);

        //3.新增sku数据
        saveSkuList(goods);
    }

    @Override
    public Goods findBySpuId(String spuId) {
        //根据spuId查询spu数据
        Spu spu = spuMapper.selectByPrimaryKey(spuId);

        //根据spuId查询sku的列表数据
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",spuId);
        List<Sku> skuList  = skuMapper.selectByExample(example);

        //封装商品数据
        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skuList);

        return goods;
    }

    @Override
    public void auditGoods(String spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);

        if (spu.getStatus()!=null){
            spu.setStatus("1");
        }

        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 构建查询对象
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 主键
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }
            // 货号
            if (searchMap.get("sn") != null && !"".equals(searchMap.get("sn"))) {
                criteria.andEqualTo("sn", searchMap.get("sn"));
            }
            // SPU名
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
            // 副标题
            if (searchMap.get("caption") != null && !"".equals(searchMap.get("caption"))) {
                criteria.andLike("caption", "%" + searchMap.get("caption") + "%");
            }
            // 图片
            if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) {
                criteria.andLike("image", "%" + searchMap.get("image") + "%");
            }
            // 图片列表
            if (searchMap.get("images") != null && !"".equals(searchMap.get("images"))) {
                criteria.andLike("images", "%" + searchMap.get("images") + "%");
            }
            // 售后服务
            if (searchMap.get("saleService") != null && !"".equals(searchMap.get("saleService"))) {
                criteria.andLike("saleService", "%" + searchMap.get("saleService") + "%");
            }
            // 介绍
            if (searchMap.get("introduction") != null && !"".equals(searchMap.get("introduction"))) {
                criteria.andLike("introduction", "%" + searchMap.get("introduction") + "%");
            }
            // 规格列表
            if (searchMap.get("specItems") != null && !"".equals(searchMap.get("specItems"))) {
                criteria.andLike("specItems", "%" + searchMap.get("specItems") + "%");
            }
            // 参数列表
            if (searchMap.get("paraItems") != null && !"".equals(searchMap.get("paraItems"))) {
                criteria.andLike("paraItems", "%" + searchMap.get("paraItems") + "%");
            }
            // 是否上架
            if (searchMap.get("isMarketable") != null && !"".equals(searchMap.get("isMarketable"))) {
                criteria.andEqualTo("isMarketable", searchMap.get("isMarketable"));
            }
            // 是否启用规格
            if (searchMap.get("isEnableSpec") != null && !"".equals(searchMap.get("isEnableSpec"))) {
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andEqualTo("isDelete", searchMap.get("isDelete"));
            }
            // 审核状态
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andEqualTo("status", searchMap.get("status"));
            }

            // 品牌ID
            if (searchMap.get("brandId") != null) {
                criteria.andEqualTo("brandId", searchMap.get("brandId"));
            }
            // 一级分类
            if (searchMap.get("category1Id") != null) {
                criteria.andEqualTo("category1Id", searchMap.get("category1Id"));
            }
            // 二级分类
            if (searchMap.get("category2Id") != null) {
                criteria.andEqualTo("category2Id", searchMap.get("category2Id"));
            }
            // 三级分类
            if (searchMap.get("category3Id") != null) {
                criteria.andEqualTo("category3Id", searchMap.get("category3Id"));
            }
            // 模板ID
            if (searchMap.get("templateId") != null) {
                criteria.andEqualTo("templateId", searchMap.get("templateId"));
            }
            // 运费模板id
            if (searchMap.get("freightId") != null) {
                criteria.andEqualTo("freightId", searchMap.get("freightId"));
            }
            // 销量
            if (searchMap.get("saleNum") != null) {
                criteria.andEqualTo("saleNum", searchMap.get("saleNum"));
            }
            // 评论数
            if (searchMap.get("commentNum") != null) {
                criteria.andEqualTo("commentNum", searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
